class Tab_Gen():
    def __init__(self, local):
        self.connected = False

        if local:
            from db import DB_Agent
            self.db = DB_Agent()
            self.path = ''
        else:
            ' try the same connection '
            from db import DB_Agent
            self.db = DB_Agent()
            self.path = '/var/www/liverbird.ru/htdocs/sites/default/files/tables/archive/test_'

    def filename(self, date):
        return self.path+'{0}_{1}_{2}.html'.format(date[0:4], date[4:6], date[6:8])

    def create_all_tables_once(self):
        assert self.connected

        for date in self.db.execute('SELECT date FROM league_table GROUP BY date;', silent = True):
            self.create_table_from_db(date[0])
       
        
    def create_table_from_db(self, date):
        assert self.connected
        
        table = self.db.execute('SELECT * FROM league_table WHERE date = {0};'.format(date), silent = True)
        assert table, 'No data found'
        
        self.generate_html(table, date)
    
    def connect(self):
        self.connected = True
        self.db.connect()
    
    def close(self):
        assert self.connected
        self.db.close()
        self.connected = False

    def find_name(self, id):
        
        clubs_list = {'Burnley': '1431', 'Chelsea': '35', 'Tottenham': '149', 'Man Utd': '39', 'Man City': '38', 'Stoke': '47', 'Arsenal': '31', 'Liverpool': '0',\
                      'Aston Villa': '32', 'Sunderland':'48', 'West Ham': '42', 'Birmingham': '1433', 'Wolverhampton': '1435', 'Hull':'37', 'Fulham': '36',\
                      'Everton': '27', 'Wigan': '46', 'Blackburn': '33', 'Bolton': '34', 'Portsmouth': '43', 
                      'Newcastle': '41', 'Norwich': '5128', 'QPR': '5144', 'Swansea': '5171', 'West Brom': '59', 'West Ham': '42', 'Reading':'2832', 'Southampton':'5161'}


        for item in clubs_list.keys():
            if int(clubs_list[item]) == id:
                return item
        else:
            assert False, id

    def generate_html(self, table, date):
    
        destination = open(self.filename(date), 'w', encoding = 'utf-8')  
        print ('Writing table to ', self.filename(date))
        destination.write('<h2>Table for date {0}</h2>'.format(self.filename(date)))

        for line in sorted(table):
            string = '{0} <b>{1}</b> {2} <b>{3}</b><br>'.format(line[1], self.find_name(line[2]),  line[3:-1], line[-1])
            destination.write(string)

        destination.close()



